import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';

/// 图片错误处理工具类
class ImageErrorHandler {
  // 使用默认缓存管理器
  static final customCacheManager = DefaultCacheManager();

  /// 创建一个网络图片组件，并提供错误处理
  static Widget networkImage({
    required String url,
    double? width,
    double? height,
    BoxFit fit = BoxFit.cover,
    BorderRadius? borderRadius,
  }) {
    // 检查width和height是否为有效值（不是NaN或Infinity）
    final safeWidth = width != null && width.isFinite ? width : null;
    final safeHeight = height != null && height.isFinite ? height : null;
    
    // 计算安全的内存缓存尺寸
    final memCacheWidth = safeWidth?.toInt();
    final memCacheHeight = safeHeight?.toInt();

    return ClipRRect(
      borderRadius: borderRadius ?? BorderRadius.zero,
      child: CachedNetworkImage(
        imageUrl: url,
        width: safeWidth,
        height: safeHeight,
        fit: fit,
        cacheManager: customCacheManager,
        // 图片内存缓存选项，使用安全值
        memCacheWidth: memCacheWidth,
        memCacheHeight: memCacheHeight,
        // 错误处理
        errorWidget: (context, url, error) {
          // debugPrint('图片加载错误: $url - $error');
          return Container(
            width: safeWidth,
            height: safeHeight,
            color: Colors.grey.shade200,
            child: Center(
              child: Icon(
                Icons.broken_image_outlined,
                color: Colors.grey,
                size: (safeWidth ?? 24) / 2,
              ),
            ),
          );
        },
        // 加载中占位
        progressIndicatorBuilder: (context, url, downloadProgress) {
          return Container(
            width: safeWidth,
            height: safeHeight,
            color: Colors.grey.shade100,
            child: Center(
              child: CircularProgressIndicator(
                value: downloadProgress.progress,
                strokeWidth: 2,
              ),
            ),
          );
        },
      ),
    );
  }

  /// 创建一个圆形网络头像组件，并提供错误处理
  static Widget networkAvatar({
    required String url,
    double radius = 20,
  }) {
    // 检查radius是否为有效值
    final safeRadius = radius.isFinite ? radius : 20.0;
    
    // 计算安全的内存缓存尺寸
    final double memCacheSize = safeRadius * 2;
    final memCacheSizeInt = memCacheSize.isFinite ? memCacheSize.toInt() : 40;

    return CircleAvatar(
      radius: safeRadius,
      backgroundColor: Colors.grey.shade200,
      child: ClipOval(
        child: CachedNetworkImage(
          imageUrl: url,
          width: safeRadius * 2,
          height: safeRadius * 2,
          fit: BoxFit.cover,
          cacheManager: customCacheManager,
          memCacheWidth: memCacheSizeInt,
          memCacheHeight: memCacheSizeInt,
          errorWidget: (context, url, error) {
            debugPrint('头像加载错误: $url - $error');
            return Icon(
              Icons.person,
              color: Colors.grey,
              size: safeRadius * 1.2,
            );
          },
          progressIndicatorBuilder: (context, url, downloadProgress) {
            return Center(
              child: CircularProgressIndicator(
                value: downloadProgress.progress,
                strokeWidth: 2,
              ),
            );
          },
        ),
      ),
    );
  }
  
  /// 清除图片缓存
  static Future<void> clearImageCache() async {
    // 清除内存缓存
    imageCache.clear();
    imageCache.clearLiveImages();
    // 清除磁盘缓存
    await customCacheManager.emptyCache();
  }
} 